<template>
  <div class="pressrelease" :style="{ height: getHeight }">
    <el-scrollbar>
      <div class="pressrelease1">
        <div class="upload">
          <el-upload ref="uploadI" action="/path/common/upload" list-type="picture-card" :on-success="handleSuccess"
            :on-exceed="handleExceed" :on-progress="uploadProcess" :before-upload="beforeUpload" :limit="1">
            <el-icon>
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png/mp4 只支持这三种文件格式，文件要小于 100MB 哦！
              </div>
            </template>
            <template #file="{ file }">
              <div>
                <video class="el-upload-list__item-thumbnail" :src="file.url" v-if="showvideo(file)"></video>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" v-if="showimage(file)" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon>
                      <zoom-in />
                    </el-icon>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handleRemove(file, uploadI)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <el-image v-if="!showasider" style="width: 600px; height: 400px" :src="dialogImageUrl" fit="scale-down" />
            <video :src="dialogImageUrl" v-if="showasider" :width="600" :height="400" controls></video>
          </el-dialog>

          <div class="publish-news">
            <el-form ref="ruleFormRef" :model="form" label-position="top" size="large" status-icon :rules="rules"
              hide-required-asterisk>
              <el-form-item label="新闻标题" prop="newsTitle">
                <el-input v-model="form.newsTitle" />
              </el-form-item>
              <el-form-item label="新闻描述" prop="newsDesc">
                <el-input v-model="form.newsDesc" type="textarea" rows="5" placeholder="<----请输入新闻的相关描述---->" />
              </el-form-item>
              <el-form-item label="新闻内容" prop="newsContent">
                <el-input v-model="form.newsContent" type="textarea" rows="5" placeholder="<----请输入新闻的内容---->" />
              </el-form-item>
              <el-form-item v-if="store.identity != 1" label="新闻属性" prop="newsIsCheck">
                <el-checkbox v-model="form.newsIsCheck">是否校验</el-checkbox>
                <el-checkbox v-model="form.newsIsTop">是否置顶</el-checkbox>
                <el-checkbox v-model="form.newsIsRot">是否为热点新闻</el-checkbox>
                <el-checkbox v-model="form.newsIsRecommend">是否为推荐新闻</el-checkbox>
              </el-form-item>
              <el-form-item label="发布时间" prop="newsDate">
                <el-date-picker v-model="form.newsDate" type="datetime" placeholder="发布时间" format="YYYY/MM/DD hh:mm:ss"
                  value-format="YYYY-MM-DDThh:mm:ss" />
              </el-form-item>
              <el-form-item label="新闻栏目" prop="categoryId">
                <el-select v-model="form.categoryId" class="m-2" placeholder="新闻栏目" size="large">
                  <el-option v-for="item in option" :key="item.categoryId" :label="item.categoryName"
                    :value="item.categoryId" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit(ruleFormRef)" style="margin-left:12vw">发布新闻</el-button>
                <el-button @click="resetForm(ruleFormRef)" style="margin-left:10vw">重新编辑</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="right-image">
          <el-image :src="imageurl" fit="fill" style="width:100%;height:100%; border-radius: 0 10px 10px 0;"></el-image>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">

import { ref, reactive, onMounted } from 'vue'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles, UploadProgressEvent, UploadRawFile, FormInstance, UploadInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import api from '../../api/api'
import { usestore } from '../../store'

const store = usestore()

const dialogImageUrl = ref('')

const dialogVisible = ref(false)

const showasider = ref(false)

let getHeight = ref('')

const option = ref<any[]>([])

const imageurl = "https://guet-lab.oss-cn-hangzhou.aliyuncs.com/api/2022/12/16/174a9fd4-a3d3-4edb-b09d-45637fc51e89.png"

const ruleFormRef = ref<FormInstance>()

const uploadI = ref<UploadInstance>()


const form = reactive({
  newsTitle: '',
  newsDesc: '',
  newsContent: '',
  newsCount: 0,
  newsDate: '',
  newsImagePath: '',
  newsIsCheck: false,
  newsIsTop: false,
  newsIsRot: false,
  newsIsRecommend: false,
  newsClassification: '图片新闻',
  categoryId: undefined
})


const rules = reactive<FormRules>({
  newsTitle: [{
    required: true,
    message: '请输入新闻标题！',
    trigger: 'blur'
  }],

  newsDesc: [{
    required: true,
    message: '请输入新闻的相关描述',
    trigger: 'blur'
  }],

  newsContent: [{
    required: true,
    message: '请输入新闻的相关描述',
    trigger: 'blur'
  }],
  categoryId: [{
    required: true,
    message: '请选择一个栏目',
    trigger: 'change'
  }],
  newsDate: [{
    required: true,
    message: '请选择新闻发布时间',
    trigger: 'change'
  }]

})


const handleRemove = (file: UploadFile, upload: UploadInstance | undefined) => {
  if (!upload) return
  upload.handleRemove(file)
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  if (file.name.split(".")[1] == "mp4") {
    showasider.value = true
  } else {
    showasider.value = false
  }
  dialogVisible.value = true
}

const uploadProcess = (evt: UploadProgressEvent, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log("...uploading");
}

const handleSuccess = (res: any, File: UploadFile) => {
  if (res.code == 200) {
    form.newsImagePath = res.data
    ElMessage({
      showClose: true,
      type: 'success',
      message: `${File.name}上传成功！`,
    })
  } else {
    ElMessage({
      showClose: true,
      type: 'error',
      message: `${File.name}文件上传失败，请重新上传！`,
    })
  }
}

const beforeUpload = (rawFile: UploadRawFile) => {
  const isLt100M = rawFile.size / 1024 / 1024 < 100;
  if (['video/mp4', 'image/jpeg', 'image/png'].indexOf(rawFile.type) == -1) {
    ElMessage({
      showClose: true,
      message: '请上传正确的文件格式,.mp4、.png、.jpg',
      type: 'error',
    })
    return false;
  }
  if (!isLt100M) {
    ElMessage({
      showClose: true,
      message: '上传文件大小不能超过100MB哦!',
      type: 'error'
    })
    return false;
  }
}

const handleExceed = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  ElMessage.warning(
    `限制了上传的文件为 1 个文件`
  )
}

const showvideo = (file: any) => {
  return Boolean(file.name.split(".")[1] == "mp4")
}

const showimage = (file: any) => {
  return Boolean(file.name.split(".")[1] == "png" || file.name.split(".")[1] == "jpg")
}


const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.NewsAddNews(form).then(
        res => {
          if (res.data.code == 200) {
            ElMessage({
              message: '新增新闻成功',
              type: 'success'
            })
            form.newsIsTop = false
            form.newsIsRot = false
            form.newsIsRecommend = false
            if (!formEl) return
            formEl.resetFields()
          }
        }).catch(err => console.log(err))
      console.log(form);
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  form.newsIsTop = false
  form.newsIsRot = false
  form.newsIsRecommend = false
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {

  api.selectallcategory()
    .then(res => {
      if (res.data.code == 200) {
        option.value = res.data.data
      }
    }).catch(err => console.log(err))
  getHeight.value = window.innerHeight - 116 + 'px'
  window.onresize = () => {
    getHeight.value = window.innerHeight - 116 + 'px'
  }
})

</script>

<style scoped>
.pressrelease1 {
  display: flex;
  justify-content: space-between;
}

.upload {
  background-color: #ffffff;
  border-radius: 10px 0 0 10px;
  padding: 10px;
}

.right-image {
  flex: 1;
}

.publish-news {
  width: 50vw;
  margin-top: 1vh;
}
</style>